package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * TimeTag类
 * 实现时间标签的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class TimeTag implements AxdrType {

    private byte[] dataCode = null;
    private TI ti = null;
    private Date_time_s dts = null;

    public TimeTag() {
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setDtsTi(Date_time_s dts, TI ti) {
        this.dts = dts;
        this.ti = ti;
    }

    public void setDTS(Date_time_s dts) {
        this.dts = dts;
    }

    public void setTI(TI ti) {
        this.ti = ti;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        int codeLength = 0;

        dts = new Date_time_s();
        codeLength += dts.decode(input);

        ti = new TI();
        codeLength += ti.decode(input);

        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                try {
                    output.write(this.dataCode[i]);
                } catch (java.io.IOException e) {
                    throw new RuntimeException("IO exception during encode", e);
                }
            }
        } else {
            if (this.ti != null && this.dts != null) {
                codeLength = 0;
                codeLength += this.ti.encode(output);
                codeLength += this.dts.encode(output);
            } else {
                throw new RuntimeException("ti or dts is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    @Override
    public String toString() {
        if (this.ti != null && this.dts != null) {
            return "sequence: {" + "dts: " + this.dts + ", ti: " + this.ti + "}";
        } else {
            return "ti or dts is null";
        }
    }
}